package com.zys.background.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zys.background.common.entity.Result;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

/**
 * @author zys
 * @apiNote 全局过滤器
 * @since 2022-11-25
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BgGlobalFilter implements GlobalFilter {
  private static final String AUTH_PATH = "/auth";
  private static final ObjectMapper MAPPER = new ObjectMapper();
  private static final Result<Void> FAIL = Result.fail("token 未找到");
  @Override
  @SneakyThrows
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    String path = request.getPath().value();
    if (path.startsWith(AUTH_PATH)) {
      return chain.filter(exchange);
    }

    HttpHeaders headers = request.getHeaders();
    List<String> authorization = headers.get("Authorization");
    if (Objects.isNull(authorization) || Objects.isNull(authorization.get(0))) {
      ServerHttpResponse response = exchange.getResponse();
      response.setStatusCode(HttpStatus.OK);
      response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
      byte[] bytes = MAPPER.writeValueAsString(FAIL).getBytes();
      DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
      return response.writeWith(Mono.just(dataBuffer));
    }
    log.info("访问的 ip: {}, 路径: {}", headers.get("Host"), path);

    return chain.filter(exchange);
  }
}
